package com.fh.controller.system.web3jTest;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.List;

import org.web3j.crypto.CipherException;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.crypto.Wallet;
import org.web3j.crypto.WalletFile;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.ObjectMapperFactory;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fh.controller.base.BaseController;
import com.fh.util.web3jsw.Web3jGeth;

public class web3jTests extends BaseController {
     
//	public static void main(String[] args) {
//		try{
//			ECKeyPair keyPair = Keys.createEcKeyPair();
//			String privateKey = keyPair.getPrivateKey().toString(16);
//			String publicKey = keyPair.getPublicKey().toString(16);
//			String account = Keys.getAddress(keyPair);
//			
//			System.out.println(account);
//			
//			String pass = "123";
//			File destDir = new File("D:\\dsddsf");
//			String fn = WalletUtils.generateWalletFile(pass,keyPair,destDir,true);
//			
//			
//			List<String> accounts = Web3jGeth.getAccountlist();
//			String from = accounts.get(0);
//			String to = accounts.get(1);
//			BigInteger gasPrice = null;
//			BigInteger gasLimit = null;
//			BigInteger value = BigInteger.valueOf(100L); //wei
//			BigInteger nonce = null;
//			String data = null;
//			Transaction tx = new Transaction(from,nonce,gasPrice,gasLimit,to,value,data);
//			Web3j web3j=Web3jGeth.initWeb3j();
//			String txHash =web3j.ethSendTransaction(tx).send().getTransactionHash();
//			System.out.println(txHash);
//		List<String> list = Web3jGeth. getAccountlist();
//		for(int i=0;i<list.size();i++){
//			System.out.println(list.get(i));
//		}
//			
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//		
//	}
	
	public static void getssw(String id)throws Exception{
		
	Web3j web3j = Web3j.build(new HttpService("https://172.31.158.:8545"));

	String address = "0x86d92bf27a82b84571494d9c7d3361b6f3c66bc3";

	EthGetBalance ethGetBalance = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST).send();

	if(ethGetBalance!=null){

	// 打印账户余额

	System.out.println(ethGetBalance.getBalance());

	// 将单位转为以太，方便查看

	System.out.println(Convert.fromWei(ethGetBalance.getBalance().toString(), Convert.Unit.ETHER));

	}
	}
	
	
	public static String getss(){
		String walletFileName0="";//文件名
	    String walletFilePath0="D:\\";
	    //钱包文件保持路径，请替换位自己的某文件夹路径

	    try {
			walletFileName0 = WalletUtils.generateNewWalletFile("123456", new File(walletFilePath0), false);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	    //WalletUtils.generateFullNewWalletFile("password1",new File(walleFilePath1));
	    //WalletUtils.generateLightNewWalletFile("password2",new File(walleFilePath2));
	    System.out.println("walletName: "+walletFileName0);
	    return walletFileName0;

	}
	
	public static String readToString(String fileName) {  
        String encoding = "UTF-8";  
        File file = new File(fileName);  
        Long filelength = file.length();  
        byte[] filecontent = new byte[filelength.intValue()];  
        try {  
            FileInputStream in = new FileInputStream(file);  
            in.read(filecontent);  
            in.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } 
        try {  
            return new String(filecontent, encoding);  
        } catch (Exception e) {  
            System.err.println("The OS does not support " + encoding);  
            e.printStackTrace();  
            return null;  
        }  
    }  
	
	// 创建钱包调用此方法
	public static String generateNewWalletFile(
	        String password, File destinationDirectory, boolean useFullScrypt){
		try{
			  ECKeyPair ecKeyPair = Keys.createEcKeyPair(); // ---------- 创建私钥
			    return generateWalletFile(password, ecKeyPair, destinationDirectory, useFullScrypt);
		}catch (Exception e) {
			// TODO: handle exception
		}
		return password;
	  
	}

	
	//导入钱包调用此方法
	public static String generateWalletFile(
	     String password, ECKeyPair ecKeyPair, File destinationDirectory, boolean useFullScrypt)
	     throws CipherException, IOException {
	
	 WalletFile walletFile; // ---------- web3j 提供的钱包文件类, 推荐阅读源码
//	 if (useFullScrypt) {
	     walletFile = Wallet.createStandard(password, ecKeyPair);
//	 } else {
//	     walletFile = Wallet.createLight(password, ecKeyPair);
//	 }
	
	 String fileName = "aaa.json";
	 File destination = new File(destinationDirectory, fileName);
	
	 ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
	 objectMapper.writeValue(destination, walletFile);
	
	 return fileName;
	}
    
	
	
	 public static void main(String[] args) throws Exception {
		 getssw("http://192.168.1.3:8545");
//		 File a = new File("D:\\");
//		 generateNewWalletFile("111",a,true);
		// loadWallet();
//		 String ab = getss();
//		String a =  readToString("D:/"+ab);
//		StringBuilder str =new StringBuilder(a);
//		String removestr= ",\"kdf\":\"scrypt\"";
//		int b = a.indexOf(removestr);
//		System.out.println(b);
//		str.replace(279,294, "");
//		System.out.println(str);
//		File file =new File("D:/"+ab);
//		file.delete();
//		s(str,ab);
	 }
	 public static void s (StringBuilder str,String ab)throws Exception{
		 FileOutputStream outSTr = null;
		 BufferedOutputStream Buff = null;
		 outSTr = new FileOutputStream(new File("D:/"+ab));
         Buff = new BufferedOutputStream(outSTr);
         long begin0 = System.currentTimeMillis();
         for (int i = 0; i < 1; i++) {
             Buff.write(str.toString().getBytes());
         }
         Buff.flush();
         Buff.close();
         long end0 = System.currentTimeMillis();
         System.out.println("BufferedOutputStream执行耗时:" + (end0 - begin0) + " 毫秒");
         loadWallet("D:/"+ab);
	 }
	 
	 
	 private static void loadWallet(String walleFilePaths) throws IOException, CipherException {
//		    String walleFilePath="D:/UTC--2018-04-10T02-51-24.815000000Z--12571f46ec3f81f7ebe79112be5883194d683787.json";
//		  String walleFilePath="D:/dsddsf1.json";
		    String passWord="123456";
		    Credentials  credentials = WalletUtils.loadCredentials(passWord, walleFilePaths);
		    String address = credentials.getAddress();
		    BigInteger publicKey = credentials.getEcKeyPair().getPublicKey();
		    BigInteger privateKey = credentials.getEcKeyPair().getPrivateKey();

		    System.out.println("address="+address);
		    System.out.println("public key="+publicKey);
		    System.out.println("private key="+privateKey);

		}


//	
//	  public static void main(String[] args) throws Exception {
//		           BigInteger GAS_PRICE = BigInteger.valueOf(22_000_000_000L);
//		           BigInteger GAS_LIMIT = BigInteger.valueOf(4_300_000);
//		  
//		           Web3j web3j = Web3j.build(new HttpService("http://192.168.1.3:8545"));
//		           String ownAddress = "0x7d5098baa6da28caceb8d576ecdf3ee8090702b9";
//		           //被转人账户地址
//		           String toAddress = " 0x23CDfDbB56b634b5dEb0Aa7A1aDcD2b7011d408b";
//		           //转账人私钥
//		           ECKeyPair ecKeyPair = Keys.createEcKeyPair();
//		            BigInteger privateKeyInDec = ecKeyPair.getPrivateKey();
//		            String sPrivatekeyInHex = privateKeyInDec.toString(16);
//		            System.out.println(sPrivatekeyInHex);
//		            
//		            
//		            System.out.println();//钱包地址
//		            
//		           Credentials credentials = Credentials.create(sPrivatekeyInHex);
//		           //        Credentials credentials = WalletUtils.loadCredentials(
//		           //                "123",
//		           //                "src/main/resources/UTC--2018-03-01T05-53-37.043Z--d1c82c71cc567d63fd53d5b91dcac6156e5b96b3");
//		   
//		           //getNonce（这里的Nonce我也不是很明白，大概是交易的笔数吧）
//		           EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
//		                   ownAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
//		           BigInteger nonce = ethGetTransactionCount.getTransactionCount();
//		   
//		           //创建交易，这里是转0.5个以太币
//		           BigInteger value = Convert.toWei("1", Convert.Unit.ETHER).toBigInteger();
//		           RawTransaction rawTransaction = RawTransaction.createEtherTransaction(
//		                   nonce, GAS_PRICE, GAS_LIMIT, toAddress, value);
//		   
//		           //签名Transaction，这里要对交易做签名
//		           byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
//		           String hexValue = Numeric.toHexString(signedMessage);
//		   
//		          //发送交易
//		           EthSendTransaction ethSendTransaction =
//		                 web3j.ethSendRawTransaction(hexValue).sendAsync().get();
//		           String transactionHash = ethSendTransaction.getTransactionHash();
//		   
//		          //获得到transactionHash后就可以到以太坊的网站上查询这笔交易的状态了
//		           System.out.println(transactionHash);
//		       }
}
